<?php
/**
 * 星悦媒体中心库通知接口类
 * Created by www.soe-soe.com
 * Author: shijy
 * Date: 2016/7/7
 * Time: 11:18
 */

namespace Common\Model\OtherSystem;

use Common\Model\LogModel;
use Common\Model\UtilsModel;

class starCenter extends NoticeOtherSystem
{
    const KEY='hzxhbyg4gjjyyqqkkdgzsmshjjj1000hzgdbuytszs800hb';
    private $noticeUrl='';


    public function __construct()
    {
        $this->noticeUrl=MEDIA_CENTER_URL.'api.php?';
    }

    /**
     * 格式化参数，对数值型转为字符型
     * Author: shijy
     * @param $param
     * @return mixed
     */
    private function format_param($param){
        foreach($param as $k=>$v){
            if(is_numeric($v)){
                $param[$k]=$v.'';
            }elseif(is_array($v) || is_object($v)){
                $param[$k]=$this->format_param($v);
            }
        }
        return $param;
    }

    /**
     * cgi方式请求数据
     * Author: shijy
     * @param $actionName
     * @param $param
     * @return bool|mixed
     */
    public function notice_cgi($actionName,$param=null)
    {
        $param=$this->format_param($param);
        $now=time();
        $sign=$this->mkSign($now,$param);
        list($c,$a)=explode('_',$actionName);
        $url=$this->noticeUrl."c={$c}&a={$a}&sign={$sign}&t={$now}";

        LogModel::dailyLog($actionName,$url);
        LogModel::dailyLog($actionName,$param);
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if(is_null($param)){
            curl_setopt($ch, CURLOPT_HEADER, 0);
        }else{
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, array('data'=>json_encode($param)));
        }
        $resultStr = curl_exec($ch);
        LogModel::dailyLog($actionName,$resultStr);
        if(is_null($resultStr)){
            $this->addNoticeOtherSystemLog(COMPANY_JCH,$actionName,$param,0,NoticeOtherSystem::STATUS_FAILURE_SYSTEM);
            return false;
        }

        $resultObj=json_decode($resultStr,true);

        if(!$resultObj){
            $this->addNoticeOtherSystemLog(COMPANY_JCH,$actionName,$param,$resultStr,NoticeOtherSystem::STATUS_FAILURE_FEEDBACK);
            return false;
        }
        $this->addNoticeOtherSystemLog(COMPANY_JCH,$actionName,$param,$resultStr,NoticeOtherSystem::STATUS_SUCCESS);
        return $resultObj;
    }

    /**
     * sign算法
     * Author: shijy
     * @param $actionName 行为名称
     * @param $timestamp 时间戳
     * @param $param  将被post的数据
     * @return string sign签名
     */
    public function mkSign($timestamp,$param=null){
        $temp=array();
        $temp['sk']    = self::KEY;
        $temp['t']     = $timestamp;
        if(!is_null($param)){
            $temp['data']  =md5(json_encode($param));
        }
        ksort($temp);
        $paramStr=http_build_query($temp);
         return md5($paramStr);
    }



    
}